package com.pateo.bjev.contacts;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.pateo.bjev.contacts.adapter.BtPagerFragmentAdapter;
import com.pateo.bjev.contacts.fragment.CallLogFragment;
import com.pateo.bjev.contacts.fragment.ContactsFragment;
import com.pateo.bjev.contacts.fragment.TwelveKeyFragment;
import com.pateo.bjev.contacts.service.ContactService;
import com.pateo.bjev.contacts.utils.CallUtils;
import com.pateo.bjev.contacts.utils.Log;
import com.pateo.bjev.contacts.view.TabLayout;
import com.pateo.bluetooth.logic.bean.ContactData;
import com.pateo.bluetooth.logic.bean.ContactLog;
import com.pateo.bluetooth.logic.contact.manager.ContactsManager;

import java.util.List;

public class MainActivity extends FragmentActivity implements TabLayout.OnTabSelectedListener,ServiceConnection{

    private static final String TAG = "MainActivity";

    TabLayout tabLayout;

    ViewPager pager;
    BtPagerFragmentAdapter adapter;
    BjevContactsManager manager;

    CallLogFragment callLogFragment;
    ContactsFragment contactsFragment;
    TwelveKeyFragment twelveKeyFragment;

    View name_search_action;
    MainSearchPlugin searchPlugin;

    View sync_layout;
    TextView sync_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sync_layout = findViewById(R.id.sync_layout);
        sync_info = (TextView) findViewById(R.id.sync_info);

        initTabs();
        initPager();

        searchPlugin = new MainSearchPlugin(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
    }

    @Override
    public void onBackPressed() {
        if(tabLayout.getVisibility() == View.GONE){
            switchSearch(false);
            return;
        }
        super.onBackPressed();
    }

    private void initTabs(){
        tabLayout = (TabLayout) findViewById(R.id.tablayout);

        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_title_calllog));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_title_contacts));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_title_twelveKey));

        tabLayout.setOnTabSelectedListener(this);

        name_search_action = findViewById(R.id.toolbar_search);
        name_search_action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchSearch(true);
            }
        });

        findViewById(R.id.input_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchSearch(false);
            }
        });
    }

    private void switchSearch(boolean visiable){
        Transition transition = TransitionInflater.from(this).inflateTransition(R.transition.switch_search);
        TransitionManager.beginDelayedTransition((ViewGroup) findViewById(R.id.toolbar_main),transition);
        if(visiable){
            tabLayout.setVisibility(View.GONE);
            findViewById(R.id.toolbar_search_layout).setVisibility(View.GONE);
            findViewById(R.id.search_name_input_layout).setVisibility(View.VISIBLE);
        }else{
            tabLayout.setVisibility(View.VISIBLE);
            findViewById(R.id.toolbar_search_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.search_name_input_layout).setVisibility(View.GONE);
        }
        searchPlugin.active(visiable);
    }

    private void initPager(){
        Fragment[] fragments = new Fragment[3];
        fragments[0] = callLogFragment = new CallLogFragment();
        fragments[1] = contactsFragment = new ContactsFragment();
        fragments[2] = twelveKeyFragment = new TwelveKeyFragment();
        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new BtPagerFragmentAdapter(getSupportFragmentManager(),fragments);
        pager.setAdapter(adapter);

        pager.addOnPageChangeListener(tabLayout);
    }

    private void bindService(){
        Intent intent = new Intent(this, ContactService.class);
        bindService(intent,this,BIND_AUTO_CREATE);
    }

    @Override
    public void onTabSelected(int position) {
        pager.setCurrentItem(position);
    }

    IPbapStateListener listener = new IPbapStateListener.Stub() {
        @Override
        public void onCalllogSyncStart() throws RemoteException {
            sync_layout.setVisibility(View.VISIBLE);
            sync_info.setText(getString(R.string.sync_info,getString(R.string.tab_title_calllog)));
        }

        @Override
        public void onCalllogProgress(int progress, int all) throws RemoteException {

        }

        @Override
        public void onCalllogSyncEnd(List<ContactLog> list) throws RemoteException {
            callLogFragment.switchCallLogs(true);
            sync_layout.setVisibility(View.GONE);
        }

        @Override
        public void onContactsSyncStart() throws RemoteException {
            sync_layout.setVisibility(View.VISIBLE);
            sync_info.setText(getString(R.string.sync_info,getString(R.string.tab_title_contacts)));
        }

        @Override
        public void onContactsProgress(int progress, int all) throws RemoteException {

        }

        @Override
        public void onContactsSyncEnd(List<ContactData> list) throws RemoteException {
            contactsFragment.switchContacts(true);
            sync_layout.setVisibility(View.GONE);
        }

        @Override
        public void onCallLogUpdated(List<ContactLog> list) throws RemoteException {
            callLogFragment.loadCallLogs(list);
        }

        @Override
        public void onContactUpdated(List<ContactData> list) throws RemoteException {
            contactsFragment.logContacts(list);
        }
    };

    IBtStateListener btListener = new IBtStateListener.Stub() {
        @Override
        public void connected() throws RemoteException {
            Log.d(MainActivity.class,"bt connected!");
        }

        @Override
        public void disconnected() throws RemoteException {
            Log.d(MainActivity.class,"bt disconnected!");
            callLogFragment.switchCallLogs(false);
            contactsFragment.switchContacts(false);
        }
    };

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.i(MainActivity.class,"onServiceConnected");
        if(iBinder!=null){
            manager = BjevContactsManager.Stub.asInterface(iBinder);
            try {
                manager.registerPbapSyncListener(listener);
                manager.registerBtStateListener(btListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.i(MainActivity.class,"onServiceDisconnected");
    }

    public BjevContactsManager getManager(){
        return manager;
    }

    public void toBtSetting(){
//        Intent intent = new Intent();
//        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
//        startActivity(intent);
    }
}
